<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称" >{{props.newSpuInfo.spuName}}</el-form-item>
    <el-form-item label="SKU名称">
      <el-input placeholder="SKU名称" v-model="newSkuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格">
      <el-input type="number" placeholder="请输入价格" v-model="newSkuInfo.price"></el-input>
    </el-form-item>
    <el-form-item label="重量">
      <el-input type="number" placeholder="请输入重量" v-model="newSkuInfo.weight"></el-input>
    </el-form-item>
    <el-form-item label="规格描述">
      <el-input type="textarea" rows="4" placeholder="规格描述" v-model="newSkuInfo.skuDesc"></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form label-width="80px" :inline="true">
        <el-form-item :label="attr.attrName" v-for="attr in attrsList" :key="attr.id">
          <el-select placeholder="请选择" v-model="attr.attrValue">
            <el-option :value="`${item.attrId}:${item.id}`" v-for="item in attr.attrValueList" :key="item.id" :label="item.valueName"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性" >
      <el-form label-width="80px" :inline="true">
        <el-form-item :label="sale.saleAttrName" v-for="sale in SaleAttrList" :key="sale.id" >
          <el-select placeholder="请选择" v-model="sale.saleAttrValueTem">
            <el-option :value="`${saleAttr.baseSaleAttrId}:${saleAttr.id}`" v-for="saleAttr in sale.spuSaleAttrValueList" :key="saleAttr.id" :label="saleAttr.saleAttrValueName"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片列表">
      <el-table border stripe :data="SpuImgList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column label="图片">
          <template v-slot="{row}">
            <img :src="row.imgUrl" alt="" width="100" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="default" size="default" v-if="row.isDefault === 1"></el-button>
              <el-button type="primary" @click="changeIsDefault(row)">设为默认</el-button>
            </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item label="">
      <el-button type="primary" @click="savaSkuInfo">保存</el-button>
      <el-button type="default" @click="emit('changeShowState', 0)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">

import { defineComponent } from "vue";


export default defineComponent({
  name: "SkuForm",
});
</script>

<script setup lang="ts">
import {ref,onMounted} from 'vue'
import { requestBaseSaleAttrList, requestSpuImgList,requestSpuSaleAttrList,type BaseSaleAttrListType,type SpuImgListType,type SpuInfoType, type SpuSaleAttrListType } from "@/api/spu";
import {requestAttrButeList, type AttrButeListType} from '@/api/attr'
import { requestSaveSkuInfo, type SkuAttrValueListType, type SkuImageItemType, type SkuInfoItemType, type SkuSaleAttrValueItemType, type SkuSaleAttrValueListType } from '@/api/sku';
import { storeToRefs } from "pinia";
import useAttrStore from "@/stores/attr";
import { ElMessage } from 'element-plus';
//点击添加SPU按钮,跳到SPUForm页面(子传父State)
const emit = defineEmits<{
  (event: "changeShowState", state: number): void;
}>();
const props = defineProps<{ newSpuInfo: SpuInfoType }>();

const AttrStore = useAttrStore()
const {category1Id, category2Id, category3Id} =storeToRefs(AttrStore)


//初始化一些值，保存请求的数据
const  attrsList = ref<AttrButeListType>([]) //平台属性
const  SaleAttrList = ref<SpuSaleAttrListType>([]) //销售属性
const  SpuImgList = ref<SpuImgListType>([]) //图片列表

//并发请求
const getInitData = async () => {
  const promise1 = requestAttrButeList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  );
  const promise2 = requestSpuSaleAttrList(props.newSpuInfo.id as number);
  const promise3 = requestSpuImgList(props.newSpuInfo.id as number);

  const result = await Promise.all([promise1, promise2, promise3]);

  attrsList.value = result[0]
  SaleAttrList.value = result[1]
  SpuImgList.value = result[2]
};

//初始化请求
onMounted(() => {
  getInitData()
})

//创建一个数据收集表单的内容
const newSkuInfo = ref<SkuInfoItemType>({
  //双向绑定内容
  price: 0,
  skuName:'',
  skuDesc: '',
  weight: '',
  
  //props中可以获取下面的数据
  spuId: 0,
  tmId: 0,
  category3Id: 0,

  //默认图片的地址，需要计算获得
  skuDefaultImg: '',
  
  //需要收集的列表数据
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
})

//收集图片列表
//创建一个新数据，因为如果修改勾选后，更改了数据，列表就无法显示
//多选会收集为一个数组
const SkuImgList =ref<SpuImgListType>([])
//定义类型
interface ImgListType{
  id: number,
  imgName: string,
  imgUrl: string,
  spuId:number
}
const handleSelectionChange=(val:ImgListType[])=>{
  console.log(val,'111');
  //拿到的就是勾选数据的信息
  SkuImgList.value = val
}

//点击默认按钮遍历图片，排他。
const changeIsDefault=(row:SkuImageItemType)=>{
  // console.log(row);
  //排他，先让请求的数据中的图片列表所有的变成0，然后让当前点击的row中的变成1
  SpuImgList.value.forEach(item => {
     //给数据中增加一个isDefault属性可选
      item.isDefault = '0'
  });
  //当前的为1
  row.isDefault = '1'
}

//收集newSkuInfo的整体数据
const savaSkuInfo = async()=>{
   //获取props传递过来的数据
   newSkuInfo.value.spuId = props.newSpuInfo.id
   newSkuInfo.value.tmId = props.newSpuInfo.tmId as number
   newSkuInfo.value.category3Id = props.newSpuInfo.category3Id
   
   //收集平台数据
  //给收集的数据绑定一个参数，添加到类型定义中，用来收集select绑定点选数据
  attrsList.value.forEach((item)=>{
    //判断当点击后，数据中就会多一个自己新增数据
    if(item.attrValue){
      //如果存在则需要解构出里面的值
      const [attrId,valueId] = item.attrValue.split(':')
      //创建一个新数据接收这两个值
      const newAttr={
        // 因为切割后是字符串，隐士转换
        attrId: +attrId,
        valueId: +valueId
      };
      //然后把数据添加到初始数据中
      (newSkuInfo.value.skuAttrValueList as SkuAttrValueListType).push(newAttr)
    }
  })
  

  //收集销售属性
  SaleAttrList.value.forEach(item=>{
      if(item.saleAttrValueTem){
        const [saleAttrId,saleAttrValueId]= item.saleAttrValueTem.split(':')
        const newSaleAttrAndValueId = {
          saleAttrId:+saleAttrId,
          saleAttrValueId:+saleAttrValueId
        };
        (newSkuInfo.value.skuSaleAttrValueList as SkuSaleAttrValueListType).push(newSaleAttrAndValueId)
      }
    })

  //收集图片数据
  SkuImgList.value.forEach(item=>{
      //收集完成后的图片列表遍历
      //创建一个新值
      const newSkuImg = {
      imgName: item.imgName,
      imgUrl: item.imgUrl,
      spuImgId: item.id,
      isDefault: item.isDefault,
    };

    //判断当里面有默认图片时
    if(item.isDefault==='1'){
      // 则直接添加到初始数据的默认图片中
      newSkuInfo.value.skuDefaultImg=item.imgUrl
    }

    //把新创的值添加给初始数据图片列表
    (newSkuInfo.value.skuImageList as SpuImgListType).push(newSkuImg)
  })


  //数据收集完发请求
   try{
    await requestSaveSkuInfo(newSkuInfo.value);
    ElMessage.success("新增sku成功");
    emit("changeShowState", 0);
   }catch(e){
    ElMessage.error("新增sku失败");
   }
}
</script>